import React, { useEffect, useState } from 'react';
import { Button, message, Space, Spin } from 'antd';
import { connect } from 'umi';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import type { IDataSourceType, IProps } from './type';
import { ApplyModal, List } from './components/index';
import styles from './index.less';
import { monthTableDataService } from '../MonthlSettlement/service';
import { havePermissions } from './tool';
import _ from 'lodash';

const MonthSettlement = (props: IProps) => {
  const { buttonPermissions, queryValue, activeMonthFetch, setState, marketList } = props;
  const [dataSource, setDataSource] = useState<IDataSourceType>();
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isError, setIsError] = useState<boolean>(false);
  const [pages, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [tableData, setTableData] = useState<any>([]);

  // 初始化获取数据
  const fetchData = async (pageData: any = null) => {
    setIsLoading(true);
    // will 查询
    const res: any = await monthTableDataService({
      ...queryValue,
      page: pageData ? pageData.pages : pages,
      size: pageData ? pageData.pageSize : pageSize,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setDataSource(res?.data || {});
      setTableData(res?.data?.rowData || []);
      setIsError(false);
    } else {
      message.error(res?.message || '查询失败');
      setIsError(true);
    }
    setState({
      activeMonthFetch: false,
    });
    setIsLoading(false);
  };

  useEffect(() => {
    (async () => {
      if (activeMonthFetch) {
        await fetchData();
      }
    })();
  }, [activeMonthFetch]);
  // 字段管理
  const handleApply = async () => {
    // 权限控制
    const resoult = havePermissions('SettlementDataDisplayMonthField', buttonPermissions);
    if (resoult) {
      const result: any = await ApplyModal.show({
        queryValue,
        fetchData,
        marketList,
        onOk: async () => {
          await fetchData();
        },
      });
      if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
        await fetchData();
      }
    }
  };

  const handleAdd = () => {
    if (tableData.some((i: any) => i.recordId?.startsWith('new-'))) {
      return;
    }
    const newRow: any = {};
    dataSource?.columnHeaders.map((i: any) => {
      if (i.fieldTitle === '附件') {
        newRow[i.id + ''] = [];
      } else {
        newRow[i.id + ''] = '';
      }
    });
    newRow.isEdit = true;
    newRow.recordId = _.uniqueId('new-');
    setTableData([newRow, ...tableData]);
  };

  return (
    <div className={styles.container}>
      <div className={styles.main}>
        <div className={styles.header}>
          <div className={styles.title}>市场结算披露</div>
          <Space>
            <Button className={styles.button} onClick={handleAdd}>
              新增
            </Button>
            <Button type="primary" className={styles.button} onClick={handleApply}>
              字段管理
            </Button>
          </Space>
        </div>
        <div className={styles.bottom}>
          {isLoading ? (
            <Spin className={styles.spin} />
          ) : isError ? (
            <TRDefault type={'error'} message={'系统异常'} />
          ) : dataSource && (dataSource.columnHeaders.length > 0 || tableData.length > 0) ? (
            <List
              dataSource={dataSource}
              fetchData={fetchData}
              pages={pages}
              pageSize={pageSize}
              setPage={setPage}
              setTableData={setTableData}
              tableData={tableData}
              setPageSize={setPageSize}
              marketId={queryValue.marketId}
            />
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ global }: any) => ({
  global,
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(MonthSettlement);
